//
//  LostSettingViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/18.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "LostSettingViewController.h"

@interface LostSettingViewController ()

/** 周选择器 **/
@property(nonatomic,strong) SetTimeWeekView *setTimeWeekView;
/** 提示 **/
@property(nonatomic,strong) UILabel *tipsLabel;

/** 开始 **/
@property(nonatomic,strong) UILabel *startLabel;
@property(nonatomic,strong) UILabel *endLabel;
@property(nonatomic,strong) UILabel *startTimeLabel;
@property(nonatomic,strong) UILabel *endTimeLabel;
/** 删除按钮 **/
@property(nonatomic,strong) UIButton *deleteButton;
@end

@implementation LostSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)refreshBaseControlValue {
    [self setNavigationTitle:@"防丢时段" titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F9"];
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    [self setRightButtonTitle:@"保存"];
    
    [self masLayout];
    
    if (self.type == 1) {
        self.deleteButton.hidden = YES;
    }
}



- (void)masLayout {
    __weak UIView *superView = self.view;
    int count = 3;
    UIView *lastView = nil;
//    NSArray *array = @[self.tipsLabel,self.startTimeLabel,self.sexLabel,self.heightLabel,self.weightLabel,self.ageLabel];
    for(int i = 0;i < count;++i ){
        //创建一个View
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:view];
        
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithHexString:@"#D0D3DC"];
        
        UIImageView *arrow = [[UIImageView alloc] init];
        arrow.image = [UIImage imageNamed:@"icon_more_nor"];
        
        [superView addSubview:line];
        [view addSubview:arrow];
//        [view addSubview:title];
        //向subView添加约束
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            make.height.mas_equalTo(px1920Height(2));
            
            //判断是否有前一个子View
            if ( lastView ) {
                //如果有前一个View，上边界和前一个View的下边界紧贴
                make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(170));
            } else {
                //如果没有前一个View，上边界和container的下边界紧贴
                make.top.mas_equalTo(self.view.mas_top).with.offset(64+px1920Height(100));
            }
        }];
        
        
        if (i == 0) {
            [superView addSubview:self.tipsLabel];
            [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(line).with.offset(-px1920Height(20));
                make.left.equalTo(superView).with.offset(px1080Width(50));
                make.right.equalTo(superView).with.offset(-px1080Width(50));
                make.height.mas_equalTo(px1080Width(50));
            }];
        } else if (i == 1) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(line);
                make.width.equalTo(self.view);
                make.height.mas_equalTo(px1920Height(170));
            }];
            
            [view addSubview:self.startLabel];
            [view addSubview:self.startTimeLabel];
            
            [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.right.equalTo(self.view).with.offset(-px1080Width(30));
                make.width.height.mas_equalTo(px1080Width(80));
            }];
            
            [self.startLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.startTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.startLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
            
        } else if (i == 2){
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(line);
                make.width.equalTo(self.view);
                make.height.mas_equalTo(px1920Height(170));
            }];
            
            [view addSubview:self.endLabel];
            [view addSubview:self.endTimeLabel];
            
            [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.right.equalTo(self.view).with.offset(-px1080Width(30));
                make.width.height.mas_equalTo(px1080Width(80));
            }];
            
            [self.endLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.endTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.endLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];

        }
        //保存前一个View
        lastView = line;
    }

    
    [self.setTimeWeekView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(40));
        make.width.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(340));
    }];
    
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.setTimeWeekView.mas_bottom).with.offset(px1920Height(451));
        make.left.mas_equalTo(superView).with.offset(px1080Width(48));
        make.right.mas_equalTo(superView).with.offset(-px1080Width(48));
        make.height.mas_equalTo(px1920Height(148));
    }];
}



#pragma mark -- 事件
- (void)onRightButtonClick:(id)sender {
    if ([self.startLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"开始时间不能为空"];
        return;
    }
    
    if ([self.endTimeLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"结束时间不能为空"];
        return;
    }
    
    if ([self compareStartTime:self.startTimeLabel.text andEndTime:self.endTimeLabel.text]) {
        [SVProgressHUD showErrorWithStatus:@"结束时间不能小于开始时间"];
        return;
    }
    
    if ([self.startTimeLabel.text isEqualToString:self.endTimeLabel.text]) {
        [SVProgressHUD showErrorWithStatus:@"开始时间不能和结束时间相同"];
        return;
    }

    [self saveLost];

}

- (void)saveLost {
    if (self.lostModel != nil) {
        self.lostModel.startTime = self.startTimeLabel.text;
        self.lostModel.endTime = self.endTimeLabel.text;
        self.lostModel.repeat = [self.setTimeWeekView getButtonSelected];
//        self.lostModel.time = [[NSDate date] timeIntervalSince1970];
        self.lostModel.switchMark = YES;
        self.lostModel.time = [self zeroOfDate];
        
        if ([[self.setTimeWeekView getButtonSelected] isEqualToString:@"永不"]) {
            DTCSAVE_OBJECT(@"YES", @"onlyOne"); // 只报警一次
        }
        
        if ([self.lostModel updateObject]) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
            if (self.updateBlock) {
                self.updateBlock();
            }
        }

    } else {
        LostModel *lost = [[LostModel alloc] init];
        lost.startTime = self.startTimeLabel.text;
        lost.endTime = self.endTimeLabel.text;
        lost.repeat = [self.setTimeWeekView getButtonSelected];
//        lost.time = [[NSDate date] timeIntervalSince1970];
        lost.switchMark = YES;
        lost.time = [self zeroOfDate];
        if ([lost insertObject]) {
            if ([[self.setTimeWeekView getButtonSelected] isEqualToString:@"永不"]) {
                DTCSAVE_OBJECT(@"YES", @"onlyOne"); // 只报警一次
            }
            
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
            if (self.updateBlock) {
                self.updateBlock();
            }
        }

    }

}


- (NSInteger)zeroOfDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    NSDate *startDate = [calendar dateFromComponents:components];
    return [[NSNumber numberWithDouble:[startDate timeIntervalSince1970]] integerValue];
}
//- (void)saveLost {
//    NSMutableArray *array = [[NSMutableArray alloc] init];
//    [array addObjectsFromArray:DTCEXRACT_OBJECT(@"lost")];
//    if (self.dict != nil) { // 修改
//        for (int i = 0; i < array.count ;i++) {
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:array[i]];
//            if ([dic[@"time"] isEqualToString:self.dict[@"time"]]) {
//                [array removeObject:dic];
//                NSDictionary *dict = @{@"startTime":self.startTimeLabel.text,@"endTime":self.endTimeLabel.text,@"repeat":[self.setTimeWeekView getButtonSelected],@"time":[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]],@"switch":@"YES"};
//                [array addObject:dict];
//                DTCSAVE_OBJECT(array, @"lost");
//                if ([[self.setTimeWeekView getButtonSelected] isEqualToString:@"永不"]) {
//                    DTCSAVE_OBJECT(@"YES", @"onlyOne"); // 只报警一次
//                }
//                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//                [self.navigationController popViewControllerAnimated:YES];
//
//                if (self.updateBlock) {
//                    self.updateBlock();
//                }
//            }
//        }
//        
//    } else { // 新增
//        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary: @{@"startTime":self.startTimeLabel.text,@"endTime":self.endTimeLabel.text,@"repeat":[self.setTimeWeekView getButtonSelected],@"time":[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]],@"switch":@"YES"}];
//        [array addObject:dict];
//        DTCSAVE_OBJECT(array, @"lost");
//        if ([[self.setTimeWeekView getButtonSelected] isEqualToString:@"永不"]) {
//            DTCSAVE_OBJECT(@"YES", @"onlyOne"); // 只报警一次
//        }
//        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//        [self.navigationController popViewControllerAnimated:YES];
//        
//        if (self.updateBlock) {
//            self.updateBlock();
//        }
//    }
//}

- (BOOL)compareStartTime:(NSString *)startTime andEndTime:(NSString *)endTime {
    NSInteger start = [self getYearMouthDayWithTime:startTime];
    NSInteger end = [self getYearMouthDayWithTime:endTime];
    
    if (start > end) { // 开始时间大于结束时间
        return YES;
    } else {
        return NO;
    }
}



// 将某个时间点转换成时间戳
- (NSInteger)getYearMouthDayWithTime:(NSString *)time {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *formatTime = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:date],time];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date2 = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date2 timeIntervalSince1970]] integerValue];
    return timeSp;
}


- (void)didClickDeleteButton {
    if ([self.lostModel deleteObject]){
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
        if (self.updateBlock) {
            self.updateBlock();
        }
    }
}

- (void)showStartTimeChoose {
    NSDate *date = [NSDate date];
    [[DTPickerManager shareManager]showDate:date pickerWithTimeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.startTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",[arr[0]intValue],[arr[1]intValue]];
    }];
    
    
}

- (void)showEndTimeChoose {
    NSDate *date = [NSDate date];
    [[DTPickerManager shareManager]showDate:date pickerWithTimeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.endTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",[arr[0]intValue],[arr[1]intValue]];
    }];
}

#pragma mark 懒加载
- (SetTimeWeekView *)setTimeWeekView
{
    if(!_setTimeWeekView)
    {
        __weak UIView *superView = self.view;
        _setTimeWeekView = [[SetTimeWeekView alloc]init];
        _setTimeWeekView.repeat = self.lostModel.repeat;
        [superView addSubview:_setTimeWeekView];
    }
    return _setTimeWeekView;
}


- (UILabel *)startLabel
{
    if(!_startLabel)
    {
//        __weak UIView *superView = self.view;
        _startLabel = [[UILabel alloc]init];
//        [superView addSubview:_startLabel];
        [_startLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_startLabel setTextColor:[UIColor colorWithHexString:@"#3E76F6"]];
        _startLabel.text = @"始";
    }
    return _startLabel;
}
- (UILabel *)endLabel
{
    if(!_endLabel)
    {
//        __weak UIView *superView = self.view;
        _endLabel = [[UILabel alloc]init];
//        [superView addSubview:_endLabel];
        [_endLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_endLabel setTextColor:[UIColor colorWithHexString:@"F6663E"]];
        _endLabel.text = @"终";
    }
    return _endLabel;
}
- (UILabel *)startTimeLabel
{
    if(!_startTimeLabel)
    {
//        __weak UIView *superView = self.view;
        _startTimeLabel = [[UILabel alloc]init];
//        [superView addSubview:_startTimeLabel];
        [_startTimeLabel setFont:[UIFont systemFontOfSize:px1080Width(64)]];
        [_startTimeLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        if (self.lostModel == nil) {
            _startTimeLabel.text = @"08:00";
        } else {
            _startTimeLabel.text = self.lostModel.startTime;
        }
        _startTimeLabel.userInteractionEnabled = YES;
        [_startTimeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showStartTimeChoose)]];

    }
    return _startTimeLabel;
}
- (UILabel *)endTimeLabel
{
    if(!_endTimeLabel)
    {
//        __weak UIView *superView = self.view;
        _endTimeLabel = [[UILabel alloc]init];
//        [superView addSubview:_endTimeLabel];
        [_endTimeLabel setFont:[UIFont systemFontOfSize:px1080Width(64)]];
        [_endTimeLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        if (self.lostModel == nil) {
            _endTimeLabel.text = @"22:00";
        } else {
            _endTimeLabel.text = self.lostModel.endTime;
        }
        _endTimeLabel.userInteractionEnabled = YES;
        [_endTimeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showEndTimeChoose)]];
    }
    return _endTimeLabel;
}
- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
//        __weak UIView *superView = self.view;
        _tipsLabel = [[UILabel alloc]init];
//        [superView addSubview:_tipsLabel];
        [_tipsLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_tipsLabel setTextColor:[UIColor colorWithHexString:@"9295A0"]];
        _tipsLabel.text = @"在此时间段内，水杯断开蓝牙连接后将会报警";
    }
    return _tipsLabel;
}

- (UIButton *)deleteButton
{
    if(!_deleteButton)
    {
        __weak UIView *superView = self.view;
        _deleteButton = [[UIButton alloc]init];
        [superView addSubview:_deleteButton];
        [_deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteButton setBackgroundImage:[UIImage imageNamed:@"button_delete_nor"] forState:UIControlStateNormal];
        [_deleteButton setBackgroundImage:[UIImage imageNamed:@"button_delete_nor"] forState:UIControlStateHighlighted];
        [_deleteButton.titleLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
        [_deleteButton addTarget:self action:@selector(didClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteButton;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
